package com.zhkjnet.zhyy.job;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhkjnet.zhyy.ZhyyConfiguration;
import com.zhkjnet.zhyy.entity.*;
import com.zhkjnet.zhyy.service.AssetService;
import com.zhkjnet.zhyy.service.OilCardService;
import com.zhkjnet.zhyy.service.OilRechargeService;
import com.zhkjnet.zhyy.service.UserService;
import com.zhkjnet.zhyy.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 油卡充值定时任务
 */
@Component
public class OilRechargeJob {

    @Autowired
    private ZhyyConfiguration configuration;

    @Autowired
    private OilRechargeService oilRechargeService;

    @Autowired
    private AssetService assetService;

    private final static Logger logger = LoggerFactory.getLogger(OilRechargeJob.class);

    private final static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 确认结果，5分钟执行一次
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void result() {
        logger.info("OilRechargeJob job");
        List<OilRecharge> recharges = oilRechargeService.findAllResult(configuration.getZh().getMin());
        for (OilRecharge recharge : recharges) {
            try {
                String result = HttpUtil.post(configuration.getZh().getHost() + "/recharge/api/orderDetail?orderNo=" + recharge.getOrderNo(), "");
                Map<String, Object> map = objectMapper.readValue(result, Map.class);
                String rechargeState = (String) map.get("rechargeState");
                logger.debug("result : " + result);
                switch (rechargeState) {
                    case "0":
                        //充值中
                    case "1":
                        //充值成功
                        recharge.setStatus(RechargeStatus.Success);
                        oilRechargeService.update(recharge);
                        break;
                    default:
                        //充值失败
                        recharge.setStatus(RechargeStatus.Fail);
                        oilRechargeService.update(recharge);
                        //恢复可用资金到账号
                        Asset asset = assetService.findByUserId(recharge.getUserId());//.findAssetByOilRechargeId(recharge.getId());
                        asset.setAbleMoney(asset.getAbleMoney() + recharge.getMoney());
                        assetService.update(asset);
                        break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}